﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO.Ports;
namespace SerialComm
{
    /// <summary>
    /// GetWeight 的摘要说明
    /// </summary>
    public class GetWeight : IHttpHandler
    {
        static SerialPort port = new SerialPort();
        public bool initSerialPort(string name,int baudRate,int checkBit,int dataBit,int stopBit)
        {
            try
            {
                port.PortName = name;
                port.BaudRate = baudRate;
                port.Parity = Parity.None;
                port.DataBits = 8;
                port.StopBits = StopBits.One;
                port.Open();
                return true;
            }
            catch
            {
                return false;   
            }
            
        }

        public string GetData()
        {
            string data = String.Empty;
            if(port!=null&&port.IsOpen)
            {
                data = port.ReadLine();
            }

            return data;
           
        }

        public void ProcessRequest(HttpContext context)
        {
            if(context.Request["operate"]!=null)
            {
                string operateId = context.Request["operate"].ToString();
                if(operateId=="1")
                {
                    string portName=context.Request["comName"].ToString().Trim();
                    string BaudRate=context.Request["BaudRate"].ToString().Trim().ToString();
                    string CheckBit=context.Request["CheckBit"].ToString().Trim().ToString();
                    string DataBits=context.Request["DataBits"].ToString().Trim().ToString();
                    string StopBits=context.Request["StopBits"].ToString().Trim().ToString();

                    bool result= initSerialPort("com1", 9600, 0, 8, 1);
                    string ret = result ? "success" : "false";
                    context.Response.Write(ret);
                }

            }

           
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}